package com.ruoyi.business.controller;

import com.ruoyi.business.domain.TRegisterInfo;
import com.ruoyi.business.domain.TUserOptLog;
import com.ruoyi.business.enums.EvaluateStatusEnums;
import com.ruoyi.business.service.ITRegisterInfoService;
import com.ruoyi.business.service.ITRegisterManualService;
import com.ruoyi.business.service.ITUserOptLogService;
import com.ruoyi.business.vo.TRegisterManualVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 记录手册Controller
 *
 * @author Tellsea
 * @date 2024-02-21
 */
@Api(tags = "记录手册Controller")
@RestController
@RequestMapping("/business/registerManual")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TRegisterManualController extends BaseController {

    private final ITRegisterManualService tRegisterManualService;
    private final ITRegisterInfoService registerInfoService;
    private final ITUserOptLogService tUserOptLogService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @ApiOperation("查询记录手册列表")
    @PreAuthorize("@ss.hasPermi('business:registerManual:list')")
    @GetMapping("/list")
    public TableDataInfo<TRegisterManualVo> list(TRegisterManualVo entity) {
        return tRegisterManualService.queryList(entity);
    }

    @ApiOperation("查询记录手册所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(TRegisterManualVo entity) {
        return AjaxResult.success("查询成功", tRegisterManualService.queryAll(entity));
    }

    @ApiOperation("导出记录手册列表")
//    @PreAuthorize("@ss.hasPermi('business:registerManual:export')")
    @Log(title = "记录手册", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response, TRegisterManualVo entity) {
        List<TRegisterManualVo> list = tRegisterManualService.queryAll(entity);
        ExcelUtil<TRegisterManualVo> util = new ExcelUtil<>(TRegisterManualVo.class);
        util.exportExcel(response, list, "记录手册数据");
    }

    @ApiOperation("获取记录手册详细信息")
    @PreAuthorize("@ss.hasPermi('business:registerManual:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", tRegisterManualService.queryById(id));
    }

    @ApiOperation("新增记录手册")
    @PreAuthorize("@ss.hasPermi('business:registerManual:add')")
    @Log(title = "记录手册", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody TRegisterManualVo entity) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        boolean updateStatus = false;
        try {
            registerInfoService.updateById(new TRegisterInfo().setId(entity.getRegisterId())
                    .setEvaluateStatus(EvaluateStatusEnums.SUCCESS.getCode()));
            Long registerId = entity.getRegisterId();
            TRegisterManualVo tRegisterManualVo = tRegisterManualService.queryByRegisterId(registerId);
            if(tRegisterManualVo==null){
                updateStatus = tRegisterManualService.save(entity);
            }else{
                entity.setId(tRegisterManualVo.getId());
                updateStatus = tRegisterManualService.updateById(entity);
            }

            SysUser loginUser = SecurityUtils.getLoginUser().getUser();
            List<String> roleList = new ArrayList<>();
            if(loginUser.getRoles()!=null){
                for (SysRole role : loginUser.getRoles()) {
                    roleList.add(role.getRoleName());
                }
            }
            String optDesc = "新增记录手册";
            TUserOptLog tUserOptLog = new TUserOptLog()
                    .setOptDesc(optDesc)
                    .setOptTime(DateUtils.getNowDate())
                    .setFromUserid(loginUser.getUserId().toString())
                    .setFromUsername(loginUser.getNickName())
                    .setFromRolename(StringUtils.join(roleList,","))
                    .setToUserid(entity.getId().toString())
                    .setToUsername(entity.getCreateBy());
            tUserOptLogService.save(tUserOptLog);
            transactionManager.commit(status);
        } catch (RuntimeException e) {
            transactionManager.rollback(status);
        }
        return toAjax(updateStatus);
    }

    @ApiOperation("修改记录手册")
    @PreAuthorize("@ss.hasPermi('business:registerManual:edit')")
    @Log(title = "记录手册", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody TRegisterManualVo entity) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        boolean updateStatus = false;
        try {
            registerInfoService.updateById(new TRegisterInfo().setId(entity.getRegisterId())
                    .setEvaluateStatus(EvaluateStatusEnums.SUCCESS.getCode()));
            updateStatus = tRegisterManualService.updateById(entity);
            SysUser loginUser = SecurityUtils.getLoginUser().getUser();
            List<String> roleList = new ArrayList<>();
            if(loginUser.getRoles()!=null){
                for (SysRole role : loginUser.getRoles()) {
                    roleList.add(role.getRoleName());
                }
            }
            String optDesc = "修改记录手册";
            TUserOptLog tUserOptLog = new TUserOptLog()
                    .setOptDesc(optDesc)
                    .setOptTime(DateUtils.getNowDate())
                    .setFromUserid(loginUser.getUserId().toString())
                    .setFromUsername(loginUser.getNickName())
                    .setFromRolename(StringUtils.join(roleList,","))
                    .setToUserid(entity.getId().toString())
                    .setToUsername(entity.getCreateBy());
            tUserOptLogService.save(tUserOptLog);
            transactionManager.commit(status);
        } catch (RuntimeException e) {
            transactionManager.rollback(status);
        }
        return toAjax(updateStatus);
    }

    @ApiOperation("删除记录手册")
    @PreAuthorize("@ss.hasPermi('business:registerManual:remove')")
    @Log(title = "记录手册", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tRegisterManualService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
